/* @flow */
/* globals MessageChannel */

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIOS, isNative } from './env'

const callbacks = []
let pending = false

function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
let microTimerFunc
// macroTimerFunc 则是用来将 flushCallbacks 函数注册为 macrotasks异步任务
let macroTimerFunc
let useMacroTask = false

// 如果宿主环境支持原生 setImmediate 函数，则使用 setImmediate 注册 macrotasks
// 原生 setImmediate仅IE和edge支持，期性能优于setTimeout(timeout会不停的做超时检测)
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  macroTimerFunc = () => {
    setImmediate(flushCallbacks)
  }
// 否则 采用
} else if (typeof MessageChannel !== 'undefined' && (
  isNative(MessageChannel) ||
  // PhantomJS
  MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
  // 创建消息通道，并指定通道端口
  const channel = new MessageChannel()
  const port = channel.port2
  channel.port1.onmessage = flushCallbacks
  macroTimerFunc = () => {
    port.postMessage(1)
  }
} else {
  // 通过setTimeout降级实现nextTick(优先通过Promise来实现) 
  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

/**
 * macrotasks和microtasks均属于异步任务队列，在每一次事件循环中，macrotask只会提取一个并执行，
 * 而在同一次事件循环内会将 microtask 队列中所有的任务全部执行完毕，且要先于 macrotask
 * macrotasks类型: setTimeout, setInterval, setImmediate, I/O, UI rendering
 * microtasks类型: process.nextTick, Promise, MutationObserver
 */
// 检测当前宿主环境是否支持原生的 Promise,支持则优先使用 Promise 注册 microtask
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  // microTimerFunc 定义在文件头部，它的初始值是 undefined,
  microTimerFunc = () => {
    // 将 flushCallbacks 函数注册为 microtask
    p.then(flushCallbacks)
    // 某些情况下，microtask 没有被刷新，所以通过让浏览器注册一个microtask(什么也不做)，来间接触发microtask 的刷新
    if (isIOS) setTimeout(noop)
  }
} else {
  // 降级处理：
  microTimerFunc = macroTimerFunc
}

/**
 * Wrap a function so that if any code inside triggers state change,
 * the changes are queued using a (macro) task instead of a microtask.
 */
export function withMacroTask (fn: Function): Function {
  return fn._withTask || (fn._withTask = function () {
    useMacroTask = true
    try {
      return fn.apply(null, arguments)
    } finally {
      useMacroTask = false    
    }
  })
}

export function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {
    pending = true
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}
